package com.yishe.utils;


import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author : chusifeng
 * @version :1.0
 * :Create in 2019/12/31 10:35
 * @description: 使用Spring的BeanCopier进行属性拷贝，基于二进制字节码，性能更高
 * com.foss.cimc.atworkbs.util
 * BeanCopyUtils
 */
public class BeanCopyUtils {

    /**
     * 缓存BeanCopier，因构建该对象耗时较长
     */
    private static ConcurrentMap<String, BeanCopier> beanCopierConcurrentMap = new ConcurrentHashMap<>();

    /**
     * 工具类私有化构造器，防止无意义的创建对象
     */
    private BeanCopyUtils() {
    }

    /**
     * 传入源对象和目标对象，进行属性拷贝
     *
     * @param target 目标对象
     * @param source 源对象
     */
    public static void copy(Object target, Object source) {
        copy(target, source, null);
    }

    /**
     * 传入源对象和目标对象以及自定义转换器，进行属性拷贝
     *
     * @param target    目标对象
     * @param source    源对象
     * @param converter 自定义转换器
     */
    private static void copy(Object target, Object source, Converter converter) {
        Class sCls = source.getClass();
        Class tCls = target.getClass();
        String key = sCls.getName() + tCls.getName();
        BeanCopier copier = beanCopierConcurrentMap.get(key);
        if (null == copier) {
            copier = BeanCopier.create(sCls, tCls, null != converter);
            beanCopierConcurrentMap.put(key, copier);
        }
        copier.copy(source, target, converter);
    }
}